# coding=utf-8

import pygame


class Timer:
    def __init__(self):
        self.time_start = 0
        self.time_last = 0
        self.time_secs = 0
        self.timing = False
        self.on_change_func = None

    def start_timer(self):
        self.time_secs = 0
        self.timing = True
        self.time_start = pygame.time.get_ticks()

    def stop_timer(self):
        self.timing = False

    def set_change_func(self, func):
        self.on_change_func = func

    @staticmethod
    def str_time(time_secs):

        # 将总秒数转换为分钟和秒
        minutes = time_secs // 60
        seconds = time_secs % 60

        # 将分钟和秒格式化为 MM:SS 的形式
        time_string = "{:02}:{:02}".format(minutes, seconds)
        return time_string

    def tick_timer(self):
        #print("tick_timer(), timing = %s" % (str(self.timing)))
        if not self.timing:
            return

        self.time_secs = (pygame.time.get_ticks() - self.time_start) // 1000  # pygame中的时间以毫秒为单位

        if self.time_last != self.time_secs:
            self.time_last = self.time_secs
            if self.on_change_func:
                self.on_change_func(self.time_secs)
